{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d9eca9b3",
   "metadata": {
    "origin_pos": 1
   },
   "source": [
    "# Multiple Input and Multiple Output Channels\n",
    ":label:`sec_channels`\n",
    "\n",
    "While we described the multiple channels\n",
    "that comprise each image (e.g., color images have the standard RGB channels\n",
    "to indicate the amount of red, green and blue) and convolutional layers for multiple channels in :numref:`subsec_why-conv-channels`,\n",
    "until now, we simplified all of our numerical examples\n",
    "by working with just a single input and a single output channel.\n",
    "This allowed us to think of our inputs, convolution kernels,\n",
    "and outputs each as two-dimensional tensors.\n",
    "\n",
    "When we add channels into the mix,\n",
    "our inputs and hidden representations\n",
    "both become three-dimensional tensors.\n",
    "For example, each RGB input image has shape $3\\times h\\times w$.\n",
    "We refer to this axis, with a size of 3, as the *channel* dimension. The notion of\n",
    "channels is as old as CNNs themselves: for instance LeNet-5 :cite:`LeCun.Jackel.Bottou.ea.1995` uses them. \n",
    "In this section, we will take a deeper look\n",
    "at convolution kernels with multiple input and multiple output channels.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "1b38cfcf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:55.203128Z",
     "iopub.status.busy": "2023-08-18T19:36:55.202806Z",
     "iopub.status.idle": "2023-08-18T19:36:58.529112Z",
     "shell.execute_reply": "2023-08-18T19:36:58.525486Z"
    },
    "origin_pos": 3,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6974b13b",
   "metadata": {
    "origin_pos": 6
   },
   "source": [
    "## Multiple Input Channels\n",
    "\n",
    "When the input data contains multiple channels,\n",
    "we need to construct a convolution kernel\n",
    "with the same number of input channels as the input data,\n",
    "so that it can perform cross-correlation with the input data.\n",
    "Assuming that the number of channels for the input data is $c_\\textrm{i}$,\n",
    "the number of input channels of the convolution kernel also needs to be $c_\\textrm{i}$. If our convolution kernel's window shape is $k_\\textrm{h}\\times k_\\textrm{w}$,\n",
    "then, when $c_\\textrm{i}=1$, we can think of our convolution kernel\n",
    "as just a two-dimensional tensor of shape $k_\\textrm{h}\\times k_\\textrm{w}$.\n",
    "\n",
    "However, when $c_\\textrm{i}>1$, we need a kernel\n",
    "that contains a tensor of shape $k_\\textrm{h}\\times k_\\textrm{w}$ for *every* input channel. Concatenating these $c_\\textrm{i}$ tensors together\n",
    "yields a convolution kernel of shape $c_\\textrm{i}\\times k_\\textrm{h}\\times k_\\textrm{w}$.\n",
    "Since the input and convolution kernel each have $c_\\textrm{i}$ channels,\n",
    "we can perform a cross-correlation operation\n",
    "on the two-dimensional tensor of the input\n",
    "and the two-dimensional tensor of the convolution kernel\n",
    "for each channel, adding the $c_\\textrm{i}$ results together\n",
    "(summing over the channels)\n",
    "to yield a two-dimensional tensor.\n",
    "This is the result of a two-dimensional cross-correlation\n",
    "between a multi-channel input and\n",
    "a multi-input-channel convolution kernel.\n",
    "\n",
    ":numref:`fig_conv_multi_in` provides an example \n",
    "of a two-dimensional cross-correlation with two input channels.\n",
    "The shaded portions are the first output element\n",
    "as well as the input and kernel tensor elements used for the output computation:\n",
    "$(1\\times1+2\\times2+4\\times3+5\\times4)+(0\\times0+1\\times1+3\\times2+4\\times3)=56$.\n",
    "\n",
    "![Cross-correlation computation with two input channels.](../img/conv-multi-in.svg)\n",
    ":label:`fig_conv_multi_in`\n",
    "\n",
    "\n",
    "To make sure we really understand what is going on here,\n",
    "we can (**implement cross-correlation operations with multiple input channels**) ourselves.\n",
    "Notice that all we are doing is performing a cross-correlation operation\n",
    "per channel and then adding up the results.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c00d6d37",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.533726Z",
     "iopub.status.busy": "2023-08-18T19:36:58.533243Z",
     "iopub.status.idle": "2023-08-18T19:36:58.538930Z",
     "shell.execute_reply": "2023-08-18T19:36:58.537910Z"
    },
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def corr2d_multi_in(X, K):\n",
    "    # Iterate through the 0th dimension (channel) of K first, then add them up\n",
    "    return sum(d2l.corr2d(x, k) for x, k in zip(X, K))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff9b6556",
   "metadata": {
    "origin_pos": 9
   },
   "source": [
    "We can construct the input tensor `X` and the kernel tensor `K`\n",
    "corresponding to the values in :numref:`fig_conv_multi_in`\n",
    "to (**validate the output**) of the cross-correlation operation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4a511891",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.542978Z",
     "iopub.status.busy": "2023-08-18T19:36:58.542044Z",
     "iopub.status.idle": "2023-08-18T19:36:58.558450Z",
     "shell.execute_reply": "2023-08-18T19:36:58.555512Z"
    },
    "origin_pos": 10,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 56.,  72.],\n",
       "        [104., 120.]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],\n",
    "               [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])\n",
    "K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])\n",
    "\n",
    "corr2d_multi_in(X, K)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f543682c",
   "metadata": {
    "origin_pos": 11
   },
   "source": [
    "## Multiple Output Channels\n",
    ":label:`subsec_multi-output-channels`\n",
    "\n",
    "Regardless of the number of input channels,\n",
    "so far we always ended up with one output channel.\n",
    "However, as we discussed in :numref:`subsec_why-conv-channels`,\n",
    "it turns out to be essential to have multiple channels at each layer.\n",
    "In the most popular neural network architectures,\n",
    "we actually increase the channel dimension\n",
    "as we go deeper in the neural network,\n",
    "typically downsampling to trade off spatial resolution\n",
    "for greater *channel depth*.\n",
    "Intuitively, you could think of each channel\n",
    "as responding to a different set of features.\n",
    "The reality is a bit more complicated than this. A naive interpretation would suggest \n",
    "that representations are learned independently per pixel or per channel. \n",
    "Instead, channels are optimized to be jointly useful.\n",
    "This means that rather than mapping a single channel to an edge detector, it may simply mean \n",
    "that some direction in channel space corresponds to detecting edges.\n",
    "\n",
    "Denote by $c_\\textrm{i}$ and $c_\\textrm{o}$ the number\n",
    "of input and output channels, respectively,\n",
    "and by $k_\\textrm{h}$ and $k_\\textrm{w}$ the height and width of the kernel.\n",
    "To get an output with multiple channels,\n",
    "we can create a kernel tensor\n",
    "of shape $c_\\textrm{i}\\times k_\\textrm{h}\\times k_\\textrm{w}$\n",
    "for *every* output channel.\n",
    "We concatenate them on the output channel dimension,\n",
    "so that the shape of the convolution kernel\n",
    "is $c_\\textrm{o}\\times c_\\textrm{i}\\times k_\\textrm{h}\\times k_\\textrm{w}$.\n",
    "In cross-correlation operations,\n",
    "the result on each output channel is calculated\n",
    "from the convolution kernel corresponding to that output channel\n",
    "and takes input from all channels in the input tensor.\n",
    "\n",
    "We implement a cross-correlation function\n",
    "to [**calculate the output of multiple channels**] as shown below.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9f9f6128",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.562547Z",
     "iopub.status.busy": "2023-08-18T19:36:58.561741Z",
     "iopub.status.idle": "2023-08-18T19:36:58.567371Z",
     "shell.execute_reply": "2023-08-18T19:36:58.566249Z"
    },
    "origin_pos": 12,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def corr2d_multi_in_out(X, K):\n",
    "    # Iterate through the 0th dimension of K, and each time, perform\n",
    "    # cross-correlation operations with input X. All of the results are\n",
    "    # stacked together\n",
    "    return torch.stack([corr2d_multi_in(X, k) for k in K], 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d8dceb2a",
   "metadata": {
    "origin_pos": 13
   },
   "source": [
    "We construct a trivial convolution kernel with three output channels\n",
    "by concatenating the kernel tensor for `K` with `K+1` and `K+2`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "27621226",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.571512Z",
     "iopub.status.busy": "2023-08-18T19:36:58.570515Z",
     "iopub.status.idle": "2023-08-18T19:36:58.579033Z",
     "shell.execute_reply": "2023-08-18T19:36:58.578147Z"
    },
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([3, 2, 2, 2])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "K = torch.stack((K, K + 1, K + 2), 0)\n",
    "K.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eae4d263",
   "metadata": {
    "origin_pos": 15
   },
   "source": [
    "Below, we perform cross-correlation operations\n",
    "on the input tensor `X` with the kernel tensor `K`.\n",
    "Now the output contains three channels.\n",
    "The result of the first channel is consistent\n",
    "with the result of the previous input tensor `X`\n",
    "and the multi-input channel,\n",
    "single-output channel kernel.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4d36175c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.583043Z",
     "iopub.status.busy": "2023-08-18T19:36:58.582466Z",
     "iopub.status.idle": "2023-08-18T19:36:58.596203Z",
     "shell.execute_reply": "2023-08-18T19:36:58.593357Z"
    },
    "origin_pos": 16,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[[ 56.,  72.],\n",
       "         [104., 120.]],\n",
       "\n",
       "        [[ 76., 100.],\n",
       "         [148., 172.]],\n",
       "\n",
       "        [[ 96., 128.],\n",
       "         [192., 224.]]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "corr2d_multi_in_out(X, K)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43cccb95",
   "metadata": {
    "origin_pos": 17
   },
   "source": [
    "## $1\\times 1$ Convolutional Layer\n",
    ":label:`subsec_1x1`\n",
    "\n",
    "At first, a [**$1 \\times 1$ convolution**], i.e., $k_\\textrm{h} = k_\\textrm{w} = 1$,\n",
    "does not seem to make much sense.\n",
    "After all, a convolution correlates adjacent pixels.\n",
    "A $1 \\times 1$ convolution obviously does not.\n",
    "Nonetheless, they are popular operations that are sometimes included\n",
    "in the designs of complex deep networks :cite:`Lin.Chen.Yan.2013,Szegedy.Ioffe.Vanhoucke.ea.2017`.\n",
    "Let's see in some detail what it actually does.\n",
    "\n",
    "Because the minimum window is used,\n",
    "the $1\\times 1$ convolution loses the ability\n",
    "of larger convolutional layers\n",
    "to recognize patterns consisting of interactions\n",
    "among adjacent elements in the height and width dimensions.\n",
    "The only computation of the $1\\times 1$ convolution occurs\n",
    "on the channel dimension.\n",
    "\n",
    ":numref:`fig_conv_1x1` shows the cross-correlation computation\n",
    "using the $1\\times 1$ convolution kernel\n",
    "with 3 input channels and 2 output channels.\n",
    "Note that the inputs and outputs have the same height and width.\n",
    "Each element in the output is derived\n",
    "from a linear combination of elements *at the same position*\n",
    "in the input image.\n",
    "You could think of the $1\\times 1$ convolutional layer\n",
    "as constituting a fully connected layer applied at every single pixel location\n",
    "to transform the $c_\\textrm{i}$ corresponding input values into $c_\\textrm{o}$ output values.\n",
    "Because this is still a convolutional layer,\n",
    "the weights are tied across pixel location.\n",
    "Thus the $1\\times 1$ convolutional layer requires $c_\\textrm{o}\\times c_\\textrm{i}$ weights\n",
    "(plus the bias). Also note that convolutional layers are typically followed \n",
    "by nonlinearities. This ensures that $1 \\times 1$ convolutions cannot simply be \n",
    "folded into other convolutions. \n",
    "\n",
    "![The cross-correlation computation uses the $1\\times 1$ convolution kernel with three input channels and two output channels. The input and output have the same height and width.](../img/conv-1x1.svg)\n",
    ":label:`fig_conv_1x1`\n",
    "\n",
    "Let's check whether this works in practice:\n",
    "we implement a $1 \\times 1$ convolution\n",
    "using a fully connected layer.\n",
    "The only thing is that we need to make some adjustments\n",
    "to the data shape before and after the matrix multiplication.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6a681897",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.600014Z",
     "iopub.status.busy": "2023-08-18T19:36:58.599477Z",
     "iopub.status.idle": "2023-08-18T19:36:58.605934Z",
     "shell.execute_reply": "2023-08-18T19:36:58.604806Z"
    },
    "origin_pos": 18,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def corr2d_multi_in_out_1x1(X, K):\n",
    "    c_i, h, w = X.shape\n",
    "    c_o = K.shape[0]\n",
    "    X = X.reshape((c_i, h * w))\n",
    "    K = K.reshape((c_o, c_i))\n",
    "    # Matrix multiplication in the fully connected layer\n",
    "    Y = torch.matmul(K, X)\n",
    "    return Y.reshape((c_o, h, w))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81851edf",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "When performing $1\\times 1$ convolutions,\n",
    "the above function is equivalent to the previously implemented cross-correlation function `corr2d_multi_in_out`.\n",
    "Let's check this with some sample data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e0542628",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2023-08-18T19:36:58.612710Z",
     "iopub.status.busy": "2023-08-18T19:36:58.610896Z",
     "iopub.status.idle": "2023-08-18T19:36:58.627437Z",
     "shell.execute_reply": "2023-08-18T19:36:58.626346Z"
    },
    "origin_pos": 20,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "X = torch.normal(0, 1, (3, 3, 3))\n",
    "K = torch.normal(0, 1, (2, 3, 1, 1))\n",
    "Y1 = corr2d_multi_in_out_1x1(X, K)\n",
    "Y2 = corr2d_multi_in_out(X, K)\n",
    "assert float(torch.abs(Y1 - Y2).sum()) < 1e-6"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ececf943",
   "metadata": {
    "origin_pos": 23
   },
   "source": [
    "## Discussion\n",
    "\n",
    "Channels allow us to combine the best of both worlds: MLPs that allow for significant nonlinearities and convolutions that allow for *localized* analysis of features. In particular, channels allow the CNN to reason with multiple features, such as edge and shape detectors at the same time. They also offer a practical trade-off between the drastic parameter reduction arising from translation invariance and locality, and the need for expressive and diverse models in computer vision. \n",
    "\n",
    "Note, though, that this flexibility comes at a price. Given an image of size $(h \\times w)$, the cost for computing a $k \\times k$ convolution is $\\mathcal{O}(h \\cdot w \\cdot k^2)$. For $c_\\textrm{i}$ and $c_\\textrm{o}$ input and output channels respectively this increases to $\\mathcal{O}(h \\cdot w \\cdot k^2 \\cdot c_\\textrm{i} \\cdot c_\\textrm{o})$. For a $256 \\times 256$ pixel image with a $5 \\times 5$ kernel and $128$ input and output channels respectively this amounts to over 53 billion operations (we count multiplications and additions separately). Later on we will encounter effective strategies to cut down on the cost, e.g., by requiring the channel-wise operations to be block-diagonal, leading to architectures such as ResNeXt :cite:`Xie.Girshick.Dollar.ea.2017`. \n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Assume that we have two convolution kernels of size $k_1$ and $k_2$, respectively \n",
    "   (with no nonlinearity in between).\n",
    "    1. Prove that the result of the operation can be expressed by a single convolution.\n",
    "    1. What is the dimensionality of the equivalent single convolution?\n",
    "    1. Is the converse true, i.e., can you always decompose a convolution into two smaller ones?\n",
    "1. Assume an input of shape $c_\\textrm{i}\\times h\\times w$ and a convolution kernel of shape \n",
    "   $c_\\textrm{o}\\times c_\\textrm{i}\\times k_\\textrm{h}\\times k_\\textrm{w}$, padding of $(p_\\textrm{h}, p_\\textrm{w})$, and stride of $(s_\\textrm{h}, s_\\textrm{w})$.\n",
    "    1. What is the computational cost (multiplications and additions) for the forward propagation?\n",
    "    1. What is the memory footprint?\n",
    "    1. What is the memory footprint for the backward computation?\n",
    "    1. What is the computational cost for the backpropagation?\n",
    "1. By what factor does the number of calculations increase if we double both the number of input channels \n",
    "   $c_\\textrm{i}$ and the number of output channels $c_\\textrm{o}$? What happens if we double the padding?\n",
    "1. Are the variables `Y1` and `Y2` in the final example of this section exactly the same? Why?\n",
    "1. Express convolutions as a matrix multiplication, even when the convolution window is not $1 \\times 1$. \n",
    "1. Your task is to implement fast convolutions with a $k \\times k$ kernel. One of the algorithm candidates \n",
    "   is to scan horizontally across the source, reading a $k$-wide strip and computing the $1$-wide output strip \n",
    "   one value at a time. The alternative is to read a $k + \\Delta$ wide strip and compute a $\\Delta$-wide \n",
    "   output strip. Why is the latter preferable? Is there a limit to how large you should choose $\\Delta$?\n",
    "1. Assume that we have a $c \\times c$ matrix. \n",
    "    1. How much faster is it to multiply with a block-diagonal matrix if the matrix is broken up into $b$ blocks?\n",
    "    1. What is the downside of having $b$ blocks? How could you fix it, at least partly?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fe6166e",
   "metadata": {
    "origin_pos": 25,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/70)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  },
  "required_libs": []
 },
 "nbformat": 4,
 "nbformat_minor": 5
}